﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Security;
using System.IO.Compression;
using System.Security.Cryptography.X509Certificates;

namespace PhoneFilter
{
    public class HttpUtils
    {

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受
        }

        public static String DoGet(String url)
        {
            String html = "";
            StreamReader reader = null;
            HttpWebRequest webReqst = null;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                webReqst = WebRequest.Create(url) as HttpWebRequest;
                webReqst.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                webReqst = WebRequest.Create(url) as HttpWebRequest;
            }
            Stream stream = null;
            HttpWebResponse webResponse = null;
            try
            {
                
                webReqst.Method = "GET";
                webReqst.KeepAlive = false;
                webReqst.Timeout = 30000;
                webReqst.ReadWriteTimeout = 30000;
                webResponse = (HttpWebResponse)webReqst.GetResponse();
                if (webResponse.StatusCode == HttpStatusCode.OK && webResponse.ContentLength < 1024 * 1024)
                {
                    stream = webResponse.GetResponseStream();
                    stream.ReadTimeout = 30000;
                    if (webResponse.ContentEncoding == "gzip")
                    {
                        reader = new StreamReader(new GZipStream(stream, CompressionMode.Decompress), Encoding.Default);
                    }
                    else
                    {
                        reader = new StreamReader(stream, Encoding.GetEncoding("GB2312"));
                    }
                    html = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                string strEx = "";
                strEx = string.Format("doget Exception:{1},{0}", ex.StackTrace, ex.Message.ToString());
                System.Threading.Thread.Sleep(3000);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader = null;
                }
                if (stream != null)
                {
                    stream.Close();
                    stream = null;
                }
                if (webResponse != null)
                {
                    webResponse.Close();
                    webResponse = null;
                }
                if (webReqst != null)
                {
                    webReqst.Abort();
                    webReqst = null;
                }
            }


            return html;
        }


        public static String DoPost(String url, String Content)
        {
            string html = "";
            StreamReader reader = null;
            HttpWebRequest webReqst = null;
            Stream stream = null;
            HttpWebResponse webResponse = null;
            //如果是发送HTTPS请求    
            webReqst = WebRequest.Create(url) as HttpWebRequest;


            //webReqst.Headers.Add("Cookie",);

            // Set some reasonable limits on resources used by this request
            webReqst.MaximumAutomaticRedirections = 4;
            webReqst.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            webReqst.Credentials = CredentialCache.DefaultCredentials;
            webReqst.Method = "POST";
            webReqst.ContentType = "application/x-www-form-urlencoded";
            webReqst.KeepAlive = false;
            webReqst.Timeout = 30000;
            webReqst.AllowAutoRedirect = false;
            webReqst.ReadWriteTimeout = 30000;
            try
            {
                if (Content == null)
                {
                    Content = "";
                }
                byte[] data = Encoding.UTF8.GetBytes(Content);
                webReqst.ContentLength = data.Length;
                stream = webReqst.GetRequestStream();
                stream.Write(data, 0, data.Length);



                webResponse = (HttpWebResponse)webReqst.GetResponse();
                if (webResponse.StatusCode == HttpStatusCode.OK && webResponse.ContentLength < 1024 * 1024)
                {
                    stream = webResponse.GetResponseStream();
                    stream.ReadTimeout = 30000;
                    if (webResponse.ContentEncoding == "gzip")
                    {
                        reader = new StreamReader(new GZipStream(stream, CompressionMode.Decompress), Encoding.UTF8);
                    }
                    else
                    {
                        reader = new StreamReader(stream, Encoding.UTF8);
                    }
                    html = reader.ReadToEnd();
                }
                else if (webResponse.StatusCode == HttpStatusCode.Found)
                {
                    string location = webResponse.Headers["Location"];
                    html = location;
                }
            }
            catch (Exception ex)
            {
                string strEx = "";
                strEx = string.Format("sendhttp Exception:{1},{0}", ex.StackTrace, ex.Message.ToString());
                System.Threading.Thread.Sleep(3000);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader = null;
                }
                if (stream != null)
                {
                    stream.Close();
                    stream = null;
                }
                if (webResponse != null)
                {
                    try
                    {
                        webResponse.Close();
                        webResponse = null;
                    }
                    catch
                    {
                        ;
                    }
                }
                if (webReqst != null)
                {
                    webReqst.Abort();
                    webReqst = null;
                }


            }



            return html;
        }
    }
}
